package com.zlz.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlz.server.mapper.MenuMapper;
import com.zlz.server.pojo.Menu;
import com.zlz.server.service.IMenuService;
import com.zlz.server.utils.AdminUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author efire
 * @since 2021-01-17
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    private static final String REDIS_ADMIN_ID_PREFIX = "menu";
    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public List<Menu> getMenusByAdminId() {
        Long adminId = AdminUtil.getCurrentAdmin().getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get(REDIS_ADMIN_ID_PREFIX + adminId);
        if (CollectionUtils.isEmpty(menus)) {
            menus = menuMapper.getMenusByAdminId(adminId);
            valueOperations.set(REDIS_ADMIN_ID_PREFIX + adminId, menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusByRole() {
       return menuMapper.getMenusByRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
